/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package controller;

import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class WikipediaParser 
{
	 public String title = "";
	 public String text = "";
	 
	 /**
	  * parses a given url and constructs a wikipage object
	  * @param p_url
	  * @param p_maxParagraphs
	  * @return
	  */
	public void parseURL( String p_url, int p_maxParagraphs )
	{
		title = "";
		text = "";
		
		Document p_doc = null;
		try 
		{
			p_doc = new SAXBuilder().build(p_url);
		} catch (Exception e) {e.printStackTrace();}

		List docList = p_doc.getContent(); 
		Element body = (Element)((Element)docList.get(1)).getChildren().get(1);
		Element column_content = (Element)((Element)body.getChildren().get(0)).getChildren().get(0);
		Element content = (Element)column_content.getChildren().get(0);
		List contentchildren = content.getChildren();
		int curParagraphs = 0;
		Iterator it = contentchildren.iterator();
		Element helpel;
		while (it.hasNext()) // go through the children of div = content
		{
			helpel = (Element) it.next();	// get next children
			if (helpel.getName().equals("h1"))
			{
				title = helpel.getValue();
			}
			else if (helpel.getName().equals("div"))
			{
				if (helpel.getAttributeValue("id").equals("bodyContent"))
				{
					Iterator disambIt = helpel.getChildren().iterator();
					Iterator bodyIt = helpel.getChildren().iterator();

					while (disambIt.hasNext())
					{
						helpel = (Element)disambIt.next();
						if ((helpel.getName().equals("div"))&&(helpel.getAttributeValue("id")!=null))
						{
							if (helpel.getAttributeValue("id").equals("disambig"))
							{
								title = "disambiguation";
								curParagraphs = p_maxParagraphs; // dont check further
							} // end if div id = disambig
						} // end if div
					}
					
					while ((bodyIt.hasNext())&&(curParagraphs < p_maxParagraphs)) // iterate as long as all paragraphs are found
					{
						helpel = (Element)bodyIt.next();
						if (helpel.getName().equals("p"))
						{
							text += helpel.getValue();
							curParagraphs++;
						} // end if paragraph
					} // end iteration or max paragraphs reached	
				} // end if - bodyContent
			} // end if - div
		} // end iteration
	}
	
}
